package ute.mvc.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ute.mvc.model.Question;
import ute.mvc.model.QuestionPool;
import ute.mvc.model.Subject;
import ute.mvc.model.User;

@Repository("questionPoolDAO")
public class QuestionPoolDAOImpl implements QuestionPoolDAO {
	@Autowired
	SessionFactory sessionFactory;

	// Vinh
	public String getMaxIdInSubject(Subject subject) {
		// TODO Auto-generated method stub
		Criteria criteria = sessionFactory.getCurrentSession()
				.createCriteria(QuestionPool.class)
				.add(Restrictions.eq("subject", subject))
				.setProjection(Projections.max("questionPoolId"));
		String maxId = (String) criteria.uniqueResult();
		return maxId;
	}

	@SuppressWarnings("unchecked")
	public List<QuestionPool> getAllQuestionPool() {
		return sessionFactory.getCurrentSession()
				.createCriteria(QuestionPool.class)
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
	}

	@SuppressWarnings("unchecked")
	public List<QuestionPool> findQuestionPoolByName(String questionPoolName) {
		return sessionFactory
				.getCurrentSession()
				.createCriteria(QuestionPool.class)
				.add(Restrictions.like("questionPoolName", "%"
						+ questionPoolName + "%"))
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
	}

	public void addQuestionPool(QuestionPool questionPool) {
		sessionFactory.getCurrentSession().save(questionPool);
	}

	public void updateQuestionPool(QuestionPool questionPool) {
		sessionFactory.getCurrentSession().merge(questionPool);
	}

	public void deleteQuestionPool(QuestionPool questionPool) {
		sessionFactory.getCurrentSession().delete(questionPool);
	}

	public QuestionPool getQuestionPool(String poolId) {
		// TODO Auto-generated method stub
		return (QuestionPool) sessionFactory.getCurrentSession().get(
				QuestionPool.class, poolId);
	}

	@SuppressWarnings("unchecked")
	public List<QuestionPool> getPoolBySubjectLecturer(Subject subject,
			User lecturer) {
		// TODO Auto-generated method stub
		List<QuestionPool> list = sessionFactory.getCurrentSession()
				.createCriteria(QuestionPool.class)
				.add(Restrictions.eq("subject", subject))
				.add(Restrictions.eq("lecturer", lecturer))
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
		return list;
	}

	public QuestionPool getPoolByName(String name) {
		// TODO Auto-generated method stub
		QuestionPool pool = (QuestionPool) sessionFactory.getCurrentSession()
				.createCriteria(QuestionPool.class)
				.add(Restrictions.eq("questionPoolName", name)).uniqueResult();
		return pool;
	}
}
